//
//  DownLoadHandle.m
//  MISCloud
//
//  Created by goldeney on 13-9-18.
//  Copyright (c) 2013年 goldeneye. All rights reserved.
//

#import "DownLoadHandle.h"
#import "FileSizeFormatHelper.h"
#import "ASIHTTPRequest.h"
#import "WebGetUserInfoToHttp.h"
#import "FilePathHelper.h"
#import "DownLoadHelper.h"
#import "DownloadViewController.h"

@implementation DownLoadHandle
@synthesize fileInfoModel;
@synthesize mbProgressHUD = _mbProgressHUD;
@synthesize otherProgressHUD = _otherProgressHUD;

-(NSData*)getPostData
{
    //传递用户信息
    NSMutableString *body = [[NSMutableString alloc] initWithCapacity:0];
    NSString *sessionValue = [WebGetUserInfoToHttp getUserInfoToJSON];
    [body appendFormat:@"session=%@&",sessionValue];
    
    //删除多余的“&”字符
    if(body.length>0) [body deleteCharactersInRange:NSMakeRange(body.length - 1, 1)];
    return [body dataUsingEncoding:NSUTF8StringEncoding];
}

//字典转Json
- (NSString*)dictionaryToJson:(NSDictionary *)dic
{
    NSError *parseError = nil;
    NSData  *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

//得到可下载文件地址列表后，对每个下载文件地址进行一次请求，获取每个文件的名字和大小
- (void)startDownInteriorFile:(NSString*)filePath fileName:(NSString*)fileName
{
    //创建提示框
    MainAppDelegate *applation = [[UIApplication sharedApplication] delegate];
    [self showMBProgressHUD:applation.window labelText:@"正在创建连接"];
    
    //文件名称设置
    NSMutableString *nowFileName = [[NSMutableString alloc] init];
    if (!fileName) {
        NSArray *urlCom = [[NSArray alloc]initWithArray:[filePath pathComponents]];
        [nowFileName appendString:[urlCom lastObject]];
    } else if([[fileName pathExtension] isEqualToString:@""]){
        [nowFileName appendString:fileName];
        [nowFileName appendString:@"."];
        [nowFileName appendString:[filePath pathExtension]];
    } else {
        [nowFileName appendString:fileName];
    }
    
    //创建数据模型对象
    fileInfoModel = [[FileAttributeModel alloc] init];
    fileInfoModel.fileReceivedData=[[NSMutableData alloc] init];
    fileInfoModel.fileReceivedSize=@"0";
    fileInfoModel.fileID=@"";
    fileInfoModel.fileName=nowFileName;
    fileInfoModel.fileSize=@"未知";
    fileInfoModel.fileURL=filePath;
    fileInfoModel.isDownloading=NO;
    fileInfoModel.isP2P=NO;
    fileInfoModel.isExternalDown = NO;
    
    //连接网络，拉取文件信息
    if([fileInfoModel.fileSize isEqualToString:@"未知"]||fileInfoModel.fileSize==nil) {
        ASIHTTPRequest *httpRequest=[ASIHTTPRequest requestWithURL:[NSURL URLWithString:filePath]];
        [httpRequest setDefaultResponseEncoding:NSUTF8StringEncoding];
        [httpRequest setRequestMethod:@"POST"];
        [httpRequest addRequestHeader:@"Accept-Language" value:@"zh-CN"];
        [httpRequest addRequestHeader:@"Charset" value:@"UTF-8"];
        [httpRequest addRequestHeader:@"Connection" value:@"Keep-Alive"];
        [httpRequest setAllowCompressedResponse:NO];
        [httpRequest setTimeOutSeconds:10.0f];
        
        NSMutableData *postData = [NSMutableData dataWithData:[self getPostData]];
        [httpRequest setPostBody:postData];
        
        httpRequest.delegate=self;
        [httpRequest startAsynchronous];
    }
}

//得到可下载文件地址列表后，对每个下载文件地址进行一次请求，获取每个文件的名字和大小
- (void)startDownExternalFile:(NSString*)filePath fileName:(NSString*)fileName
{
    //创建提示框
    MainAppDelegate *applation = [[UIApplication sharedApplication] delegate];
    [self showMBProgressHUD:applation.window labelText:@"正在创建连接"];
    filePath = [filePath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    //文件名称设置
    NSMutableString *nowFileName = [[NSMutableString alloc] init];
    if (!fileName) {
        NSArray *urlCom = [[NSArray alloc]initWithArray:[filePath pathComponents]];
        [nowFileName appendString:[urlCom lastObject]];
    } else if([[fileName pathExtension] isEqualToString:@""]){
        [nowFileName appendString:fileName];
        [nowFileName appendString:@"."];
        [nowFileName appendString:[filePath pathExtension]];
    } else {
        [nowFileName appendString:fileName];
    }
    
    //创建数据模型对象
    fileInfoModel = [[FileAttributeModel alloc] init];
    fileInfoModel.fileReceivedData=[[NSMutableData alloc] init];
    fileInfoModel.fileReceivedSize=@"0";
    fileInfoModel.fileID=@"";
    fileInfoModel.fileName=nowFileName;
    fileInfoModel.fileSize=@"未知";
    fileInfoModel.fileURL=filePath;
    fileInfoModel.isDownloading=NO;
    fileInfoModel.isP2P=NO;
    fileInfoModel.isExternalDown = YES;
    
    //连接网络，拉取文件信息
    if([fileInfoModel.fileSize isEqualToString:@"未知"]||fileInfoModel.fileSize==nil) {
        ASIHTTPRequest *httpRequest=[ASIHTTPRequest requestWithURL:[NSURL URLWithString:filePath]];
        [httpRequest setDefaultResponseEncoding:NSUTF8StringEncoding];
        //[httpRequest setRequestMethod:@"POST"];
        [httpRequest addRequestHeader:@"Accept-Language" value:@"zh-CN"];
        [httpRequest addRequestHeader:@"Charset" value:@"UTF-8"];
        [httpRequest addRequestHeader:@"Connection" value:@"Keep-Alive"];
        [httpRequest setAllowCompressedResponse:NO];
        [httpRequest setTimeOutSeconds:10.0f];
        
        httpRequest.delegate=self;
        [httpRequest startAsynchronous];
    }
}

#pragma mark -
#pragma mark ASIHTTPRequestDelegate
- (void)request:(ASIHTTPRequest *)request didReceiveResponseHeaders:(NSDictionary *)responseHeaders
{
    
    int statusCode = [request responseStatusCode];
    NSError *error=[request error];
    
    //如果发生错误，就返回空
    if (!error && statusCode == 404) {
        //隐藏提示框
        [self hideMBProgressHUD];
        [request cancel];
        [request clearDelegatesAndCancel];
        
        NSLog(@"无法在服务器找到文件：%d错误",statusCode);
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"该文件已不存在！"
                                                     delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        
    } else if (!error && statusCode == 500) {
        //隐藏提示框
        [self hideMBProgressHUD];
        [request cancel];
        [request clearDelegatesAndCancel];
        
        NSLog(@"服务器发生异常：%d错误",statusCode);
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"服务器发生异常，无法下载该文件！"
                                                     delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        
    } else if (!error && statusCode == 403) {
        //隐藏提示框
        [self hideMBProgressHUD];
        [request cancel];
        [request clearDelegatesAndCancel];
        
        NSLog(@"服务器拒绝访问：%d错误",statusCode);
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"您没有权限下载该文件！"
                                                     delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        
    } else if (!error && statusCode==200) {
        //隐藏提示框
        [self hideMBProgressHUD];
        [request cancel];
        [request clearDelegatesAndCancel];
        
        //设置文件名称及大小
        fileInfoModel.fileSize=[FileSizeFormatHelper getFileSizeString:[responseHeaders objectForKey:@"Content-Length"]];
        [self downFile:fileInfoModel];
        
        //跳转下载管理
        MainAppDelegate *mDelegate = [[UIApplication sharedApplication] delegate];
        DownloadViewController *view = [[DownloadViewController alloc] init];
        [mDelegate.navigationController pushViewController:view animated:YES];
    }
    
}

-(void)requestFailed:(ASIHTTPRequest *)request
{
    int statusCode = [request responseStatusCode];
    NSLog(@"==连接服务器失败==%@ ==%d",[request error],statusCode);
    
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"创建链接失败，无法下载该文件！"
                                                 delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [alert show];
    
    
    //隐藏提示框
    [self hideMBProgressHUD];
}

#pragma mark -
#pragma mark downFile

-(void)downFile:(FileAttributeModel*)selectFileInfo
{
    //因为是重新下载，则说明肯定该文件已经被下载完，或者有临时文件正在留着，所以检查一下这两个地方，存在则删除掉
    NSString *targetPath=[[FilePathHelper getTargetFloderPath]stringByAppendingPathComponent:selectFileInfo.fileName];
    NSString *tempPath=[[[FilePathHelper getTempFolderPath]stringByAppendingPathComponent:selectFileInfo.fileName]stringByAppendingString:@".temp"];
    if([FilePathHelper isExistFile:targetPath])//已经下载过一次该音乐
    {
        self.fileInfoModel = selectFileInfo;
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"该文件已经添加到您的下载列表中了！是否重新下载该文件？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alert show];
        
        return;
    }
    
    //存在于临时文件夹里
    if([FilePathHelper isExistFile:tempPath])
    {
        self.fileInfoModel = selectFileInfo;
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"该文件已经添加到您的下载列表中了！是否重新下载该文件？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alert show];
        
        return;
    }
    selectFileInfo.isDownloading=YES;
    
    //若不存在文件和临时文件，则是新的下载
    MainAppDelegate *applation = [[UIApplication sharedApplication] delegate];
    [self showSuccessTextDialog:applation.window fileName:fileInfoModel.fileName];
    
    DownLoadHelper *downLoadHelper = [DownLoadHelper sharedInstance];
    [downLoadHelper beginRequest:selectFileInfo isBeginDown:YES];
}


#pragma mark -
#pragma mark UIAlertViewDelegate

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    DownLoadHelper *downLoadHelper = [DownLoadHelper sharedInstance];
    MainAppDelegate *applation = [[UIApplication sharedApplication] delegate];
    
    if(buttonIndex==1)//确定按钮
    {
        NSFileManager *fileManager=[NSFileManager defaultManager];
        NSError *error;
        
        NSString *targetPath=[[FilePathHelper getTargetFloderPath]stringByAppendingPathComponent:self.fileInfoModel.fileName];
        NSString *tempPath=[[[FilePathHelper getTempFolderPath]stringByAppendingPathComponent:self.fileInfoModel.fileName]stringByAppendingString:@".temp"];
        
        if([FilePathHelper isExistFile:targetPath])//已经下载过一次该音乐
        {
            [fileManager removeItemAtPath:targetPath error:&error];
            if(!error)
            {
                NSLog(@"删除文件出错:%@",error);
            }
            for(FileAttributeModel *file in downLoadHelper.finishedlist)
            {
                if([file.fileName isEqualToString:self.fileInfoModel.fileName])
                {
                    [downLoadHelper.finishedlist removeObject:file];
                    break;
                }
            }
        }
        //存在于临时文件夹里
        if([FilePathHelper isExistFile:tempPath])
        {
            [fileManager removeItemAtPath:tempPath error:&error];
            if(!error)
            {
                NSLog(@"删除临时文件出错:%@",error);
            }
        }
        
        for(ASIHTTPRequest *request in downLoadHelper.downinglist)
        {
            FileAttributeModel *FileAttributeModel=[request.userInfo objectForKey:@"File"];
            if([FileAttributeModel.fileName isEqualToString:self.fileInfoModel.fileName])
            {
                [downLoadHelper.downinglist removeObject:request];
                break;
            }
        }
        
        self.fileInfoModel.isDownloading=YES;
        self.fileInfoModel.fileReceivedSize=[FileSizeFormatHelper getFileSizeString:@"0"];
        
        [self showSuccessTextDialog:applation.window fileName:fileInfoModel.fileName];
        [downLoadHelper beginRequest:self.fileInfoModel isBeginDown:YES];
    }
}

#pragma mark -
#pragma mark MBProgressHUD

- (void)showMBProgressHUD:(UIView*)view labelText:(NSString*)labelText {
    if (!_mbProgressHUD) {
        _mbProgressHUD = [[MBProgressHUD alloc] initWithView:view];
        _mbProgressHUD.mode = MBProgressHUDModeDeterminate;
        [view addSubview:_mbProgressHUD];
    
        //如果设置此属性则当前的view置于后台
        _mbProgressHUD.dimBackground = YES;
        if (labelText) {
            _mbProgressHUD.labelText = labelText;
        } else {
            _mbProgressHUD.labelText = @"请稍等";
        }
    }
    
    //显示进度条
    [_mbProgressHUD showAnimated:YES whileExecutingBlock:^{
        float progress = 0.0f;
        while (true) {
            progress += 0.001f;
            _mbProgressHUD.progress = progress;
            usleep(10000);
            if (progress>=1.0f) progress = 0.0f;
        }
    } completionBlock:^{}];
}

- (void)showSuccessTextDialog:(UIView*)view fileName:(NSString*)labelText
{
    _otherProgressHUD = [[MBProgressHUD alloc] initWithView:view];
    _otherProgressHUD.labelText = @"已加入下载列表";
    _otherProgressHUD.mode = MBProgressHUDModeCustomView;
    _otherProgressHUD.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"download_rowlogo.png"]]; 
    [view addSubview:_otherProgressHUD];
    
    //指定距离中心点的X轴和Y轴的偏移量，如果不指定则在屏幕中间显示
    //_mbProgressHUD.yOffset = 150.0f;
    //_mbProgressHUD.xOffset = 100.0f;
    
    _otherProgressHUD.userInteractionEnabled = NO;
    [_otherProgressHUD showAnimated:YES whileExecutingBlock:^{
        usleep(1500000);
    } completionBlock:^{
        [_otherProgressHUD removeFromSuperview];
        _otherProgressHUD = nil;
    }];
}

- (void)hideMBProgressHUD
{
    if (_mbProgressHUD){
        //[_mbProgressHUD hide:YES];
        [_mbProgressHUD removeFromSuperview];
        _mbProgressHUD = nil;
    }
}

@end
